<?php

namespace s94\wechat;

class CurlFileData
{
    protected $content;
    protected $name;
    protected $mime;

    public function __construct($name, $content, $mime=null)
    {
        $this->name = $name;
        $this->content = $content;
        if (!$mime){
            if (preg_match("/\.(\w+)$/", $name, $ms)) $mime = self::suffixToMime($ms[1]);
        }
        $this->mime = $mime;
    }

    /**通过指定文件路径来构建CurlFileData
     * @param string $path 文件路径
     * @return CurlFileData
     */
    public static function getFromPath(string $path)
    {
        $content = file_get_contents($path);
        $arr = array_reverse(explode('/', $path));
        $name = null;
        foreach ($arr as $v){
            if (preg_match("/\.(\w+)$/", $v)){
                $name = $v;break;
            }
        }
        return new self($name, $content);
    }

    /**后缀名转mime类型
     * @param string $suffix 后缀名，例如：png
     * @return void
     */
    public static function suffixToMime($suffix)
    {
        $mime_map = [
            'bmp'=>'image/bmp','png'=>'image/png','jpeg'=>'image/jpeg','jpg'=>'image/jpeg','gif'=>'image/gif',
            'mp3'=>'audio/mpeg','wma'=>'audio/wma','wav'=>'audio/wav','amr'=>'audio/amr',
            'mp4'=>'video/mp4',
        ];
        $suffix = strtolower($suffix);
        return $mime_map[$suffix] ?? 'application/octet-stream'; //默认为二进制文件
    }
    // GET相关方法
    public function toArray()
    {
        return [
            'name'=> $this->name,
            'mime'=> $this->mime,
            'content'=> $this->content,
        ];
    }
    public function getName()
    {
        return $this->name;
    }
    public function getMime()
    {
        return $this->mime;
    }
    public function getContent()
    {
        return $this->content;
    }

    // SET相关方法
    public function setContent($content)
    {
        $this->content = $content;
    }
    public function setMime($mime)
    {
        $this->mime = $mime;
    }

}